﻿using Lazy.Captcha.Core;
using Lazy.Captcha.Core.Generator;
using Lazy.Captcha.Core.Storage;
using Microsoft.Extensions.Options;

namespace Devonline.AspNetCore;

/// <summary>
/// 随机验证码
/// </summary>
public class RandomCaptcha(IOptionsSnapshot<CaptchaOptions> options, IStorage storage) : DefaultCaptcha(options, storage)
{
    private static readonly Random _random = new();
    private static readonly CaptchaType[] _captchaTypes = Enum.GetValues<CaptchaType>();

    /// <summary>
    /// 修改默认验证规则
    /// </summary>
    /// <param name="options"></param>
    protected override void ChangeOptions(CaptchaOptions options)
    {
        base.ChangeOptions(options);

        // 随机验证码类型
        options.CaptchaType = _captchaTypes[_random.Next(UNIT_ZERO, _captchaTypes.Length)];

        // 当是算数运算时，CodeLength是指运算数个数
        if (options.CaptchaType.IsArithmetic())
        {
            options.CodeLength = UNIT_TWO;
        }
        else
        {
            options.CodeLength = UNIT_FOUR;
        }

        // 如果包含中文时，使用kaiti字体，否则文字乱码
        if (options.CaptchaType.ContainsChinese())
        {
            options.ImageOption.FontFamily = DefaultFontFamilies.Kaiti;
            options.ImageOption.FontSize = UNIT_EIGHT + UNIT_SIXTEEN;
        }
        else
        {
            options.ImageOption.FontFamily = DefaultFontFamilies.Actionj;
        }

        // 动静随机
        options.ImageOption.Animation = _random.Next(UNIT_TWO) == UNIT_ZERO;

        // 干扰线随机
        options.ImageOption.InterferenceLineCount = _random.Next(UNIT_ONE, UNIT_FOUR);

        // 气泡随机
        options.ImageOption.BubbleCount = _random.Next(UNIT_ONE, UNIT_FOUR);
    }
}